import { convertObj2Str } from "./util.js";
import { $redirect2Login } from "./router.js";
import { BASE_API } from "@/config/index";
import { TOKEN } from "@/config/constant";
import { $msg } from "./msg";

console.log(BASE_API);

function $request({ method, url, needAuth, header, data }) {
	return new Promise((resolve, reject) => {
		if (!url.startsWith("http")) url = BASE_API + url;
		console.log("访问了" + url);

		header = header || {};
		// 需要传token去识别身份
		if (needAuth) {
			let access_token = uni.getStorageSync(TOKEN);
			if (access_token) {
				header["token"] = access_token;
			} else {
				// return $msg("请先登录", () => {
				//   resolve({ success: false });
				//   $redirect2Login();
				// });
			}
		}

		uni.request({
			method,
			url,
			data,
			header,
			success: ({ data, statusCode }) => {
				if (!data) data = { errorCode: 200, data: null, message: "" };
				//网络500
				if (statusCode === 200) resolve(data);
				else reject(statusCode);
				//业务系统500
				switch (data.errorCode) {
					case 500:
						$msg(data.message || "网络异常,请稍后再试");
						reject(data.errorCode);
						break;
					case 4001:
					case 401:
						$msg("登录超时，请重新登录", () => {
							$redirect2Login();
						});
				}
			},
			fail: (err) => {
				console.log("接口出错", err);
				reject(err);
			},
			complete() {},
		});
	});
}

export function $get(url, data, needAuth = true) {
	return $request({
		method: "GET",
		url,
		data,
		needAuth,
	});
}

//将参数放到路径中
export function $postQ(url, data, needAuth = true) {
	let qs = convertObj2Str(data);
	if (qs) url += "?" + qs;

	return $request({ method: "POST", url, needAuth });
}

//将参数放到body中
export function $postB(url, data, needAuth = true) {
	return $request({ method: "POST", url, data, needAuth });
}

//将参数放到form中
export function $postF(url, data, needAuth = true) {
	return $request({
		method: "POST",
		url,
		data,
		needAuth,
		header: {
			"content-type": "application/x-www-form-urlencoded",
		},
	});
}

export function $upload(filePath, name = "file") {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: BASE_API + "/system/upload",
			filePath,
			name,
			header: {
				token: uni.getStorageSync(TOKEN),
			},
			complete: ({ data }) => {
				try {
					if (typeof data === "string") data = JSON.parse(data);
					resolve(data);
				} catch (e) {
					resolve(null);
				}
			},
			fail: (res) => {
				$msg("上传失败");
			},
		});
	});
}
